<template>
  <div ref="echartRef" :style="{ width: width, height: height }"></div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, PropType, watch, watchEffect, inject, Ref } from 'vue'
import * as echarts from 'echarts'
import mapNMG from './map/json/province/neimenggu.json'

export default defineComponent({
  name: 'MmEchart',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '360px'
    },
    option: {
      type: Object as PropType<echarts.EChartsOption>,
      required: true
    }
  },
  setup(props) {
    const echartRef = ref<HTMLElement>()

    // 注册地图
    echarts.registerMap('内蒙古', mapNMG)

    onMounted(() => {
      const echartInstance = echarts.init(echartRef.value!, '', { renderer: 'svg' })
      const isCollapse = inject<Ref<boolean>>('isCollapse')

      window.addEventListener('resize', () => {
        echartInstance.resize()
      })

      echartInstance.setOption(props.option)

      // 折叠左侧菜单时 echarts 自适应宽度
      watch(isCollapse!, () => {
        // 为了平滑
        // 不考虑平滑直接 setTimeout 300ms 即可
        // 300ms 是 element 左侧菜单的折叠动画的时长，
        let count = 1
        const handle = setInterval(() => {
          if (count > 15) {
            clearInterval(handle)
            return
          }
          echartInstance.resize()
          count++
        }, 20)
      })

      // 因为传过来的数据是异步请求获取的
      // 所以 option 变化时 echarts 需要重新渲染，否则传过来的数据无法展示
      watchEffect(() => {
        echartInstance.setOption(props.option)
      })
    })

    return { echartRef }
  }
})
</script>
